package com.zsummer.design.structure.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zsummer
 * 2020/3/25 21:48
 * 动态代理
 */
public class Client {

    public static void main(String[] args) {
        Animal animal = new Animal();
        EatHandler handler = new EatHandler(animal);
        Eat eat = (Eat)Proxy.newProxyInstance(Client.class.getClassLoader(), animal.getClass().getInterfaces(), handler);
        eat.eat();
    }
}

interface Eat{
    void eat();
}

class Animal implements Eat {

    @Override
    public void eat() {
        System.out.println("animal eat");
    }
}

class EatHandler implements InvocationHandler {

    Eat eat;

    public EatHandler(Eat eat) {
        this.eat = eat;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("do something before");
        Object result = method.invoke(eat, args);
        System.out.println("do something after");
        return result;
    }
}